<template>
  <div class="userInfo">
    <n-card>
      <n-page-header title="个人信息" @back="$router.back()"></n-page-header>
    </n-card>
    <br>
    <n-card>
      <!-- <n-divider /> -->
      <br>
      <n-form label-placement="left" label-width="auto" :style="{ width: '400px' }">
        <n-form-item label="头像">
          <n-avatar object-fit="cover" :src="base_url + store.userInfo.avatar" v-if="store.userInfo.avatar" :size="90"
            class="avatarNone" @click="() => $refs.fileInput.click()">
            <template #fallback>
              <div class="fallback">{{ store?.userInfo?.userName }}</div>
            </template>
          </n-avatar>
          <n-avatar object-fit="cover" :src="store.userInfo.avatar" v-else :size="90" class="avatarNone"
            @click="() => $refs.fileInput.click()">
            <div class="fallback">{{ store?.userInfo?.userName }}</div>
          </n-avatar>
        </n-form-item>
        <n-form-item label="工号">
          <n-input disabled v-model:value="form.jobNumber" placeholder="请输入工号(同为默认密码)" :allow-input="onlyAllow" />
        </n-form-item>
        <n-form-item label="姓名" required>
          <n-input v-model:value="form.userName" placeholder="请输入姓名" />
        </n-form-item>
        <n-form-item label="性别">
          <n-select v-model:value="form.sex" :options="options.sex" />
        </n-form-item>
        <n-form-item label="岗位" required>
          <n-select disabled v-model:value="form.post" :options="options.post" />
        </n-form-item>
        <n-form-item label="部门">
          <n-input disabled v-model:value="form.departmentName" />
        </n-form-item>
        <n-form-item label="电话">
          <n-input v-model:value="form.phone" placeholder="请输入电话" />
        </n-form-item>
        <n-form-item label="邮箱">
          <n-input v-model:value="form.email" placeholder="请输入邮箱" />
        </n-form-item>
        <n-form-item label="权限">
          <n-checkbox-group v-model:value="form.jurisdiction" disabled>
            <n-space item-style="display: flex;">
              <n-checkbox :value="value" :label="key" v-for="(key, value) in options.jurisdiction" :key="key" />
            </n-space>
          </n-checkbox-group>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-divider />
        <n-space>
          <!-- <n-button @click="$router.back()">取消</n-button> -->
          <n-button type="primary" @click="save" :loading="submitLoading">保存</n-button>
        </n-space>
      </template>
    </n-card>
    <input type="file" @change="changeAvatar" accept="image/*" style="display: none" ref="fileInput">
  </div>
</template>
<script setup>
import { getUserInfo, uploadFile, updateUserInfo } from "@/api"
import Store from '@/stores'
const store = Store()
const base_url = process.env.baseURL
const form = ref({})
const submitLoading = ref(false)
const onlyAllow = (value) => !value || /^[a-zA-Z0-9]+$/.test(value)
const options = ref({
  sex: [
    {
      value: "M",
      label: '男'
    },
    {
      value: "W",
      label: '女'
    }
  ],
  jurisdiction: {
    "1": "工作管理",
    "2": "车辆管理",
    "3": "地铁摄像头",
    "4": "用户管理",
    "5": "部门管理"
  },
  // 人事，检修，普通员工和管理
  post: [
    {
      value: 1,
      label: '普通员工'
    },
    {
      value: 2,
      label: '检修'
    },
    {
      value: 3,
      label: '人事'
    },
    {
      value: 4,
      label: '管理'
    },
    {
      value: 5,
      label: '司机'
    }
  ],
  // 部门
  department: []
})
function changeAvatar(e) {
  const file = e.target.files[0]
  const formdata = new FormData()
  e.target.value = ''
  formdata.append('file', file)
  console.log(file);
  uploadFile(formdata).then(res => {
    if (res.code != 200) return $message.error(res.message)
    // $message.success(res.message)
    // store.userInfo.avatar = res.url
    updateUserInfo({ avatar: res.url, _id: store.userInfo._id }).then(res => {
      // submitLoading.value = false
      if (res.code != 200) return $message.error(res.message)
      $message.success(res.message)
      getUserinfo()
    })
  })
}
// 获取个人信息
getUserinfo()
function getUserinfo() {
  getUserInfo().then(res => {
    if (res.code != 200) return $message.error(res.message)
    if (res.data) {
      store.userInfo = Object.assign(store.userInfo, res.data, { avatar: res.data.avatar })
      form.value = Object.assign(form.value, res.data)
    }
  })
}
// 保存个人信息
function save() {
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.jobNumber
  delete params.post
  delete params.departmentName
  delete params.department
  delete params.jurisdiction
  delete params.updatedAt
  delete params.createdAt
  if (!params.userName) return $message.warning('请输入姓名')
  // 中国手机号(严谨), 根据工信部2019年最新公布的手机号段
  const phone = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/
  if (params.phone && !phone.test(params.phone)) return $message.warning('请输入正确的手机号')
  // 邮箱地址(email)
  const email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
  if (params.email && !email.test(params.email)) return $message.warning('请输入正确的邮箱')
  console.log(params);
  submitLoading.value = true
  updateUserInfo(params).then(res => {
    submitLoading.value = false
    if (res.code != 200) return $message.error(res.message)
    $message.success(res.message)
    getUserinfo()
  })
}
</script>
<style lang="less" scoped>
.userInfo {
  padding: 50px;

  .avatarNone {
    cursor: pointer;
    background-color: #4086ff;

    .fallback {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>